package com.xiaojie.learn.enable.mybatis;

import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotationMetadata;
import java.util.Map;

public class MyBatisBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar, EnvironmentAware {

    private Environment environment;

    public void setEnvironment(Environment environment) {
        this.environment = environment;
    }

    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        System.out.println("here");

        final Map<String, Object> attributes = importingClassMetadata.getAnnotationAttributes(EnableMyBatis.class.getName());

        //sqlSessionFactoryBean
        BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(SqlSessionFactoryBean.class);

        beanDefinitionBuilder.addPropertyReference("dataSource", (String) attributes.get("dataSource"));
        beanDefinitionBuilder.addPropertyValue("mapperLocations",attributes.get("mapperLocations"));
        beanDefinitionBuilder.addPropertyValue("typeAliasesPackage",attributes.get("typeAliasesPackage"));

        AbstractBeanDefinition beanDefinition = beanDefinitionBuilder.getBeanDefinition();
        String beanName = (String) attributes.get("value");
        registry.registerBeanDefinition(beanName,beanDefinition);

        //MapperScannerConfigurer
        BeanDefinitionBuilder beanDefinitionBuilder2 = BeanDefinitionBuilder.genericBeanDefinition(MapperScannerConfigurer.class);

        beanDefinitionBuilder2.addPropertyValue("basePackage",attributes.get("basePackage"));

        AbstractBeanDefinition beanDefinition2 = beanDefinitionBuilder2.getBeanDefinition();
        registry.registerBeanDefinition("mapperScannerConfigurer",beanDefinition2);

    }


}
